package com.szholly.pro.watergas_server.ps.schedule;




import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;
import com.szholly.plug.form.excel.utils.StringUtil;
import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.monitor.MonitorDataType;
import com.szholly.pro.watergas_server.ps.monitor.MonitorWaterType;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import lrq.common.MyLog;
/**
 *  定时任务，定时生成工业污染源月排放量报表（废水废气）（数据来源：5分钟数据）
 * @author 张文成
 *
 */
public class CreateMonthCouData  implements Job {
	static Logger log;
	MonitorWaterType monitorWaterType=new MonitorWaterType();
	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		
		if(log == null){
			log = MyLog.getLogger("CreateMonthCouData");
		}
		 
		try {
			
			Calendar cal = Calendar.getInstance();
			//判断当前时间是否为10号，每月10号生成上一个月的排放量数据
	        if(cal.get(Calendar.DAY_OF_MONTH) != 10)
	        {
	        	return;
	        }
	        cal.add(Calendar.DAY_OF_MONTH, -9);
			
	        //获取开始时间与结束时间
			Date endTime = cal.getTime();
			cal.add(Calendar.MONTH, -1);
			Date startTime = cal.getTime();
	      
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
			String strStartTime = sdf.format(startTime);
			String strEndTime = sdf.format(endTime);
			
			String strMonth = String.format("%0" + 2 + "d", cal.get(Calendar.MONTH)+1);
			String strDATE_TEXT = cal.get(Calendar.YEAR)+"年"+strMonth+"月";
			String strParmName = "";
			
			strParmName = "03";
			CreateWeighDataAir(strStartTime,strEndTime,strDATE_TEXT,strParmName);		   
		} catch (Exception e) {
			log.error("生成工业污染源月排放量报表出错",e);
		}
	}
	
	/**
	 * 生成数据(加权平均值)
	 * 张文成
	 * 2017年05月05日
	 */
	private void CreateWeighDataAir(String StartTime,String EndTime,String DATE_TEXT,String ParmName)throws Exception{
		    log.info("开始生成废气排放量月报表(加权");
		    try{
		    	//查询工业废气同时具备NOX、O2、烟气流量的点位
		    	String sql = "select t.name,t2.device_num,t.station_category,t.FGTYPE from BC_SITE_INFO t"
		    			+ " left join BC_COLLECTION_INFO t2 on t2.site_id = t.exp_no"
		    			+ " left join (select t.site_id,count(t.name) as parmcount from BC_SITE_POLL t where t.name in ('03','S01','AIR_B01TOTAL')"
		    			+ " group by t.site_id) t3 on t3.site_id = t2.device_num"
		    			+ " where t.station_category = '4' and t3.parmcount = 3"
		    			+ " group by t.name,t2.device_num,t.station_category,t.FGTYPE";
		    	List<RowBase> rows = DataUtil.getSelectRows(sql,null);
				
				if(rows.size()>0){
					for(int i=0;i<rows.size();i++){
						RowBase row = rows.get(i);
						String MN = row.getSafeString("device_num");
						//分表
						String WATER_TYPE = row.getSafeString("STATION_CATEGORY");
						String FGTYPE = row.getSafeString("FGTYPE");
						Double fgvalue=0.0;
						if(StringUtil.IsNotNullOrEmpty(FGTYPE)){
							if(FGTYPE.equals("1")){
								fgvalue=14.9;
							}else if(FGTYPE.equals("2")){
								fgvalue=5.9;
							}else if(FGTYPE.equals("3")){
								fgvalue=9.9;
							}
						}
						String tableName="BD_MO_MIN";
					    if(StringUtil.IsNotNullOrEmpty(WATER_TYPE)&&!WATER_TYPE.equals("3")){
					    	MonitorDataType md=monitorWaterType.getWaterType(WATER_TYPE, "minute");
							tableName=md.getTableName();
					    }
					    else{
					    	tableName="BD_MO_MIN";
					    }	
						
						//当氧气 >0 且小于18.5的时候才计算，NOX均值和折算值,和烟气流量
						//查出NOX,O2，烟气流量加权数据(5分钟一条)
						//并进行相应的单位换算
						String minuteSql = "select t.datatime,t.avg as o2avg,t1.cou as flowCou,t2.avg as NOXAVG,t2.zs_avg as NOXZSAVG,\n" +
										" (t2.avg * t1.cou) as AVGFLOW ,(t2.zs_avg * t1.cou) AS ZSAvgFLOW, (t.avg * t1.cou) AS O2AVGFLOW,t.mn\n" + 
										" from "+tableName+" t\n" + 
										" left join (select datatime,cou / 1000 as cou  from "+tableName+" t\n" + 
										" left join BC_SITE_INFO t2 on t2.code=t.mn and t2.station_category='4'"+
										" where t.mn = @MN  and t.parmname = 'AIR_B01TOTAL' and t.cou > 0\n" + 
										" and t.datatime >= to_date(@StartTime, 'yyyy-mm-dd hh24:mi:ss')\n" + 
										" and t.datatime < to_date(@EndTime, 'yyyy-mm-dd hh24:mi:ss')  and (t.cou/t2.dtperiod)>0.75 \n" + 
										" group by t.datatime,t.cou ) t1 on t1.datatime = t.datatime\n" + 
										" left join (select datatime,avg,zs_avg from "+tableName+" t\n" + 
										" where t.mn = @MN and t.parmname = '03' and t.zs_avg > 0 and t.zs_avg < 550\n" + 
										" and t.datatime >= to_date(@StartTime, 'yyyy-mm-dd hh24:mi:ss')\n" + 
										" and t.datatime < to_date(@EndTime, 'yyyy-mm-dd hh24:mi:ss')\n" + 
										" group by t.datatime,t.avg,t.zs_avg ) t2 on t2.datatime = t.datatime\n" + 
										" where t.datatime >= to_date(@StartTime, 'yyyy-mm-dd hh24:mi:ss')\n" + 
										" and t.datatime < to_date(@EndTime, 'yyyy-mm-dd hh24:mi:ss')\n" + 
										" and t.mn = @MN and t.parmname = 'S01' and t.avg > 0 and t.avg < 18.5\n" + 
										" and nvl(t2.avg,'0' ) != '0' and nvl(t2.zs_avg,'0' ) != '0' and nvl(t1.cou,'0' ) != '0'\n" + 
										" group by t.datatime,t.avg,t1.cou,t2.avg,t2.zs_avg,t.mn";
						//根据5分钟数据，查出整月NOX,O2，烟气流量加权数据
						sql = "select round((TT.avg/((20.9-TT.O2_AVG)/"+fgvalue+")),2) AS ZS_AVG,tt.*"
								+" from (select round(sum(flowCou),2) as FLOW_DISPLACE_SUM,round(sum(AVGFLOW)/sum(flowCou),2) as AVG,"
								+ " count(*) as TOD,"
								+ " round(sum(O2AVGFLOW)/sum(flowCou),2) as O2_AVG,round(sum(AVGFLOW)/1000000,2) as DISPLACE_SUM"
								+ " from (" + minuteSql
								+ " ) t group by t.mn) tt";
						
				        List<GlobalParameter> pc = new ArrayList<>();
				        pc.add(new GlobalParameter("MN", MN));
				        pc.add(new GlobalParameter("StartTime", StartTime));
				        pc.add(new GlobalParameter("EndTime", EndTime));
						List<RowBase> resultRows = DataUtil.getSelectRows(sql, pc);
						if(resultRows.size()>0){
							Double AVG = resultRows.get(0).getSafeDouble("AVG");
							Double ZS_AVG = resultRows.get(0).getSafeDouble("ZS_AVG");
							Double O2_AVG = resultRows.get(0).getSafeDouble("O2_AVG");
							Double FLOW_DISPLACE_SUM = resultRows.get(0).getSafeDouble("FLOW_DISPLACE_SUM");
							Double TOD = resultRows.get(0).getSafeDouble("TOD");
							Double DISPLACE_SUM = resultRows.get(0).getSafeDouble("DISPLACE_SUM");
							
							sql = "insert into MONITOR_DATA_MONTH_COU(guid,datatime,mn,avg,zs_avg,o2_avg,"
									+" FLOW_DISPLACE_SUM,DISPLACE_SUM,TOD,PARMNAME,DATE_TEXT) "
									+" values(sys_guid(),to_date(@StartTime,'yyyy-mm-dd hh24:mi:ss'),"
									+" @MN,@AVG,@ZS_AVG,@O2_AVG,@FLOW_DISPLACE_SUM,@DISPLACE_SUM,@TOD,"
									+" @PARMNAME,@DATE_TEXT) ";
							pc.clear();
							pc.add(new GlobalParameter("StartTime", StartTime));
							pc.add(new GlobalParameter("MN", MN));
							pc.add(new GlobalParameter("AVG", AVG));
							pc.add(new GlobalParameter("ZS_AVG", ZS_AVG));
							pc.add(new GlobalParameter("O2_AVG", O2_AVG));
							pc.add(new GlobalParameter("FLOW_DISPLACE_SUM", FLOW_DISPLACE_SUM));
							pc.add(new GlobalParameter("DISPLACE_SUM", DISPLACE_SUM));
							pc.add(new GlobalParameter("TOD", TOD));
							pc.add(new GlobalParameter("PARMNAME", ParmName));
							pc.add(new GlobalParameter("DATE_TEXT", DATE_TEXT));
							DataUtil.ExecuteUpdateSql(sql, pc);	
						}
					}
				}
				log.info("生成废气排放量月报表结束(加权)");
		    }catch(Exception e)
			{
				log.error("生成废气排放量月报表出错(加权)",e);
			}
	}
	
		
	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException(
			"The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Double.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

    
}
